package com.jims.master.modules.csm.service;

import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.csm.dao.*;
import com.jims.master.modules.csm.entity.*;
import com.jims.master.modules.drug.entity.DrugInfo;
import com.jims.master.modules.drug.service.DrugInfoService;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 消耗品出库处理Service
 * @author fengyg
 * @version 2017-03-17
 */
@Service
@Transactional(readOnly = true)
public class ExpExportService extends CrudService<ExpExportDetailDao,ExpExportDetail>{
    @Autowired
    private ExpExportMasterDao exportMasterDao;
    @Autowired
    private ExpStorageDeptDao expStorageDeptDao;
    @Autowired
    private ExpExportMasterDao expExportMasterDao;
    @Autowired
    private ExpStockDao expStockDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ExpExportDetailDao expExportDetailDao;
    @Autowired
    private ExpStorageDeptService expStorageDeptService;
    @Autowired
    private DrugInfoService drugInfoService;
    @Autowired
    private ExpSupplierCataDao expSupplierCataDao;

    public Page<ExpExportDetail> findPage(Page<ExpExportDetail> page, ExpExportDetail expExportDetail) {
        return super.findPage(page, expExportDetail);
    }

    /**
     * 出库记录查询
     * @param page 分页对象
     * @param expExportDetail
     * @return
     */
    public Page<ExpExportDetail> findDetailList(Page<ExpExportDetail> page, ExpExportDetail expExportDetail) {
        expExportDetail.updateOrgId();
        expExportDetail.setPage(page);
        expExportDetail.setStorageName(UserUtils.getUser().getOrgDept().getId());  //只能查询本科室的出库记录
        List<ExpExportDetail> detailList = dao.findDetailList(expExportDetail);
        if(null != detailList && detailList.size() > 0){
            for (ExpExportDetail exportDetail : detailList) {
                ExpStorageDept expStorageDept = expStorageDeptDao.get(exportDetail.getExpExportMaster().getReceiver());
                ExpSupplierCata expSupplierCata = expSupplierCataDao.get(exportDetail.getExpExportMaster().getReceiver());
                if(null != expStorageDept){
                    exportDetail.getExpExportMaster().setReceiver(expStorageDept.getStorageName());
                }
                if(null != expSupplierCata){
                    exportDetail.getExpExportMaster().setReceiver(expSupplierCata.getSupplierJc());
                }
                if(StringUtils.isNotBlank(exportDetail.getPackageNum())){
                    exportDetail.setQuantity(exportDetail.getQuantity() / Integer.parseInt(exportDetail.getPackageNum()));
                }
            }
        }
        page.setList(detailList);
        return page;
    }
    /**
     * 出库单据查询
     * @param
     * @param expExportMaster
     * @return
     */
    public Page<ExpExportMaster> findExportList(Page<ExpExportMaster> page, ExpExportMaster expExportMaster) {
        expExportMaster.updateOrgId();
        expExportMaster.setPage(page);
        expExportMaster.setStorageId(UserUtils.getUser().getOrgDept().getId());
        List<ExpExportMaster> exportList = expExportMasterDao.findExportList(expExportMaster);
        if(null != exportList && exportList.size() > 0){
            for (ExpExportMaster exportMaster : exportList) {
                ExpStorageDept expStorageDept = expStorageDeptDao.get(exportMaster.getReceiver());
                ExpSupplierCata expSupplierCata = expSupplierCataDao.get(exportMaster.getReceiver());
                if(null != expStorageDept){
                    exportMaster.setReceiver(expStorageDept.getStorageName());
                }
                if(null != expSupplierCata){
                    exportMaster.setReceiver(expSupplierCata.getSupplierJc());
                }
            }
        }
        page.setList(exportList);
        return page;
    }

    /**
     * 出库详情查询(出库单查询，根据出库主记录ID查询出库详情)
     * @param expExportDetail
     * @return
     */
    public List<ExpExportDetail> findBymasterId(ExpExportDetail expExportDetail) {
        expExportDetail.updateOrgId();
        List<ExpExportDetail> detailList = dao.findBymasterId(expExportDetail);
        if(null != detailList && detailList.size() > 0){
            for (ExpExportDetail exportDetail : detailList) {
                if(StringUtils.isNotBlank(exportDetail.getPackageNum())){
                    exportDetail.setQuantity(exportDetail.getQuantity() / Integer.parseInt(exportDetail.getPackageNum()));
                }
            }
        }
        return detailList;
    }

    /**
     * 消耗品出库选择有库存有价格的消耗品自动补全
     * @param expInfo
     * @param orgId
     * @return
     * @author fengyg
     * @date 2017-03-17
     */
    public List<ExpExportDetail> autoExportStock(ExpInfo expInfo, String orgId, String q, String limit) {
        List<ExpExportDetail> expExportDetails = dao.autoExportStock(expInfo, orgId, q, limit,UserUtils.getUser().getOrgDept().getId());
        if(null != expExportDetails && expExportDetails.size() > 0){
            for (ExpExportDetail expExportDetail : expExportDetails) {
                ExpStock expStock = expExportDetail.getExpStock();
                if(null != expStock){
                    Double quantity = expStock.getQuantity();
                    int packageNum = Integer.parseInt(expStock.getPackageNum());
                    if(packageNum > 0){
                        double newQuantity = expStock.getQuantity() / packageNum;
                        expStock.setQuantity(newQuantity);
                    }
                }
            }
        }
        return expExportDetails;
    }

    /**
     * 消耗品出库处理
     * @param detailList
     * @return
     * @author fengyg
     */
    @Transactional(readOnly = false)
    public String saveExportList(List<ExpExportDetail> detailList){
        int num = 0;
        StringData data = new StringData();
        String printMasterId="0";
        Double money = 0.00;   //应付款
        if(null != detailList && detailList.size() > 0){
            //出库主表
            ExpExportMaster master = detailList.get(0).getExpExportMaster();
            master.preInsert();
            printMasterId=master.getId();//获取打印主表ID
            master.setStorageId(UserUtils.getUser().getOrgDept().getId());//当前库房
            master.setExportClass(DictUtils.getDictLabel(master.getExportClass(),"EXP_STOTARG_TYPE",""));
            master.updateOrgId();
            master.setDocumentNo(createDocumentNo(master));
            for (int i = 0; i < detailList.size(); i++) {
                ExpExportDetail detail = new ExpExportDetail();
                detail = detailList.get(i);
                detail.preInsert();
                detail.setMasterId(master.getId());
                detail.setItemNo((i + 1) + "");
                detail.updateOrgId();
                //保存出库明细表
                int insert = dao.insert(detail);
                if(insert > 0){
                    num += insert;
                }else{
                    return "0";
                }

                money += detail.getPurchasePrice() * detail.getQuantity()/Integer.parseInt(detail.getPackageNum()); //计算应付款

                //减库存
                ExpStock expStock = detail.getExpStock();
                expStock.setQuantity(detail.getInventory());
                int updateQuantity = expStockDao.updateStockQuantity(expStock);
                if(updateQuantity > 0){
                    num += updateQuantity;
                }else{
                    return "0";
                }
            }
            master.setAccountReceivable(money); //出库主表设置应付款
            //保存出库主表
            int insert = exportMasterDao.insert(master);
            if(insert > 0){
                num += insert;
            }else{
                return "0";
            }
        }else{
            return "-1";  //没有需要保存的数据
        }
        return printMasterId;
    }

    /**
     * 根据供货方ID(storageId)查询需要批量入库的数据
     * @param storageId 供货方ID
     * @return
     * @author fengyg
     */
    @Transactional
    public List<ExpStock> getBatchImportList(String storageId){
        List<ExpStock> list = dao.getBatchImportList(storageId, UserUtils.getUser().getOrgDept().getId(), UserUtils.getOrgId());
        if(null != list && list.size() > 0){
            for (ExpStock batchImport : list) {
                batchImport.getExpExportDetail().setPackageUnits(DictUtils.getDictLabel(batchImport.getExpExportDetail().getPackageUnits(),"SPEC_UNIT",""));
                batchImport.getExpExportDetail().setMinUnits(DictUtils.getDictLabel(batchImport.getExpExportDetail().getMinUnits(),"SPEC_UNIT",""));
                if(null != batchImport.getExpExportDetail().getSterilizationMethod()){
                    batchImport.getExpExportDetail().setSterilizationMethod(DictUtils.getDictLabel(batchImport.getExpExportDetail().getSterilizationMethod(),"STERILIZATION_METHOD",""));
                }
                batchImport.getExpExportDetail().setQuantity(batchImport.getExpExportDetail().getQuantity() / Integer.parseInt(batchImport.getExpExportDetail().getPackageNum()));
            }
        }else{
            return new ArrayList<ExpStock>();
        }
        return list;
    }

    /*
    * 根据传来的expExportMaster数据生成出库单据号
    * @ZhuQ
    * */
    public String createDocumentNo (ExpExportMaster expExportMaster){
        //根据库房获取入库单前缀
        ExpStorageDept expStorageDept=expStorageDeptDao.getByStorageCode(expExportMaster.getStorageId());
         String documentNo = expStorageDept != null ? expStorageDept.getExportNoPrefix() : "";
        //获取当前日期
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        documentNo=documentNo+ sdf.format(d);
        expExportMaster.setDocumentNo(documentNo);
        //序号
        int i = expExportMasterDao.findDocumentNo(expExportMaster);
        String num = String.valueOf(i);
        String str ="0000";
        str=str.substring(0, 4-num.length())+num;
        documentNo=documentNo+str;
        return documentNo;
    }

    //根据传来的expStock数据组装成expExportDetail数据
    public ExpExportDetail createData(ExpStock expStock,int itemNo,String masterId){
        ExpExportDetail expExportDetail=new ExpExportDetail();
        expExportDetail.setMasterId(masterId);		// 主表Id
        expExportDetail.setItemNo(String.valueOf(itemNo+1));	// 序号
        expExportDetail.setExpCode(expStock.getExpCode());		// 消耗品编码
        expExportDetail.setInfoId(expStock.getInfoId());		// expInfoId
        expExportDetail.setPackageNum(expStock.getPackageNum());		// 包装数量
        expExportDetail.setPackageSpec(expStock.getPackageSpec());		// 包装规格
        expExportDetail.setPackageUnits(expStock.getPackageUnits());		// 包装单位
        expExportDetail.setMinSpec(expStock.getMinSpec());		// 最小规格
        expExportDetail.setMinUnits(expStock.getMinUnits());		// 最小单位
        expExportDetail.setPurchasePrice(expStock.getPurchasePrice());		// 进货价
        expExportDetail.setDiscount(expStock.getDiscount());		// 折扣
        expExportDetail.setBatchNo(expStock.getBatchNo());		// 批号
        expExportDetail.setExpireDate(expStock.getExpireDate());		// 有效期

        expExportDetail.updateOrgId();		// 机构ID
        expExportDetail.preInsert();
        return expExportDetail;
    }

    /**
     * 消耗品出库数据统计
     * @param exportDate,orgId
     * @return
     * @author ZhuQ
     */
    public List<BaseDto> expExportCount(String exportDate ,String orgId){
        return expExportMasterDao.expExportCount(exportDate,orgId);
    }
    /**
     * 消耗品出库单据打印
     * @param expExportDetail
     * @return
     */
    public String expExportDetailsPrint(ExpExportDetail expExportDetail){
        User user = UserUtils.getUser();
        String deptId=null!=user.getOrgDept()?user.getOrgDept().getId():"";
        expExportDetail.setStorageId(deptId);
        List<BaseDto> list= expExportDetailDao.findDetailListPrint(expExportDetail);
        ExpExportDetail entityForNum=dao.findNumByName(expExportDetail);
        int num=entityForNum.getNum();
        Map map = new HashMap();
        String hospital = UserUtils.getUser().getCompany().getOrgName();
        String title="消耗品出库凭证";
        Double tradePriceTotal=0.0;
        Double retailPriceTotal=0.0;
        if(list.size()>0){
            BaseDto detail=list.get(0);
                ExpStorageDept drugStorageDept=expStorageDeptService.get(detail.getAsString("receiver"));
                if(null!=drugStorageDept){
                    map.put("receiver",drugStorageDept.getStorageName());//收货库房
                }
                else {
                    map.put("receiver","");
                }
            map.put("exportClass",DictUtils.getDictLabel(detail.getAsString("exportClass"), "EXP_STOTARG_TYPE", ""));//出库类别
            map.put("documentNo",detail.getAsString("documentNo"));//出库单号
            map.put("exportDate",detail.getAsString("exportDate"));//出库日期
            map.put("storageName",detail.getAsString("storageName"));//库房
            map.put("accountType",DictUtils.getDictLabel(detail.getAsString("accountType"), "ACCOUNT_TYPE", ""));//付款方式
            int i=1;
//            if("1".equals(expExportDetail.getRemarks())){
//                map.put("receiver","");
//                map.put("storageName","");
//            }
            for(BaseDto detail1:list){
                DrugInfo drugInfo=drugInfoService.get(detail1.getAsString("infoId"));
                if(drugInfo!=null&&drugInfo.getPackageSpec().equals(detail1.getAsString("packageSpec"))){
                    detail1.put("quantity",Integer.parseInt(detail1.getAsString("quantity"))/Integer.parseInt(detail1.getAsString("packageNum")));
                }
                detail1.put("minUnits",DictUtils.getDictLabel(detail.getAsString("minUnits"), "SPEC_UNIT", ""));
                detail1.put("index",Integer.toString(i++));
                detail1.put("expireDate",detail1.getAsString("expireDate"));
                Double totalTrade=Double.parseDouble(detail1.getAsString("tradePrice"))*Double.parseDouble(detail1.getAsString("quantity"));
                Double totalRetail=Double.parseDouble(detail1.getAsString("retailPrice"))*Double.parseDouble(detail1.getAsString("quantity"));
                detail1.put("totalTrade",String.format("%.2f", totalTrade));
                detail1.put("totalRetail",String.format("%.2f",totalRetail));
                tradePriceTotal+=totalTrade;
                retailPriceTotal+=totalRetail;
            }
        }
        map.put("hospital", hospital);
        map.put("lists", list);
        map.put("title",title);
        map.put("num",num);//品种数量
        map.put("tradePriceTotal",String.format("%.2f", tradePriceTotal));
        map.put("retailPriceTotal",String.format("%.2f", retailPriceTotal));
        String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/csm/expExportDetailsPrint.jasper", map, list, "expExportDetailsPrint");
        return  printPath;
    }


}
